<?php
/*
Plugin Name: WPMU Category Defaults, Search and Replace
Version: 1.2
Plugin URI: http://natureofmind.org/?p=30
Author: Deryk Wenaus
Author URI: http://www.natureofmind.org/
Description: This plugin sets category, and other defaults for new blogs. It also allows existing blogs to be updated with defaults. 
	Works in Wordpress MU 2.6+
*/

function cat_default_options() {
	global $wpdb;
	
	if (!is_site_admin()) return false;
	
	### Form Processing 
	// Update Options
	if(!empty($_POST['Submit'])) {
		$max_default_cats =  $_POST[ 'max_default_cats' ];
		update_site_option( 'max_default_cats', $max_default_cats );
		for ( $i=1; $i<=$max_default_cats; $i++) {
			update_site_option( 'default_cat_'.$i, $_POST[ 'default_cat_'.$i ] );
		}
	}
	
	// Add Categories to Blogs
	if($_POST['do']=='Add Categories') {
		$blog_list = $wpdb->get_results( "SELECT * FROM " . $wpdb->blogs. " WHERE archived = '0' AND spam = '0' AND deleted ='0'", ARRAY_A );	
		echo '<div id="message" class="updated fade"><p>The Following blogs have been updated: ';
		foreach($blog_list as $blog) {
			$blog_id = $blog['blog_id'];
			default_category( $blog_id );
			echo $blog['blog_id'].', ';
		}
		echo '</p></div>';
	}
	
	// Find and Replace Categories
	if($_POST['do']=='Find and Replace Categories' && !$_POST['find_term']==null) {
		$find_term = htmlentities(mysql_real_escape_string(trim($_POST['find_term'])));
		$replace_term = htmlentities(mysql_real_escape_string(trim($_POST['replace_term'])));
		$find_term_slug = sanitize_title( $find_term );
		$replace_term_slug = sanitize_title( $replace_term );
		$blog_list = $wpdb->get_results( "SELECT * FROM " . $wpdb->blogs. " WHERE archived = '0' AND spam = '0' AND deleted ='0'", ARRAY_A );	
		echo '<div id="message" class="updated fade"><p><b>Results for replacing <i>'.$find_term.'</i> with <i>'.$replace_term.'</i>.</b><br>';
		foreach($blog_list as $blog) {
			$blog_id = $blog['blog_id'];
			switch_to_blog( $blog_id );
			$find_match = $wpdb->get_results( "SELECT name FROM ".$wpdb->terms." WHERE name='".$find_term."' AND slug='".$find_term_slug."'" );
			$replace_match = $wpdb->get_results( "SELECT slug FROM ".$wpdb->terms." WHERE slug='".$replace_term_slug."'" );
			
			if ( $find_match && !$replace_match ) { 
				$wpdb->get_results( "UPDATE ".$wpdb->terms." SET name=REPLACE( name,'".$find_term."','".$replace_term."') WHERE name='".$find_term."' AND slug='".$find_term_slug."'" );
				
				// we need to test to see if the replace was sucessful. because SELECT is not case sensitive but REPLACE is
				if ( $wpdb->get_results( "SELECT name FROM ".$wpdb->terms." WHERE name='".$replace_term."' AND slug='".$find_term_slug."'" ) ) {
					$wpdb->get_results( "UPDATE ".$wpdb->terms." SET slug=REPLACE( slug,'".$find_term_slug."','".$replace_term_slug."') WHERE slug='".$find_term_slug."'" );
					echo "<b>SUCCESS!</b> In blog ".$blog_id.", category <i>".$find_term."</i> was renamed to <i>".$replace_term."</i>.<br>";
				} else {
					echo "A match was found in blog ".$blog_id.", but the case did not match, so the replace was not performed.<br>";
				}
				
			} elseif ( $find_match && $replace_match ) { 
				echo "<b>WARNING:</b> In Blog ".$blog_id." category <i>".$replace_term."</i> already exists, so it cannot be replaced. (duplicates are not allowed)<br>"; 
			} else {
				echo "No matches found in blog ".$blog_id.".<br>";
			}
			
			restore_current_blog();	
		}
		
		//now replace in wp_sitecategories as well
		$find_match = $wpdb->get_results( "SELECT cat_name FROM wp_sitecategories WHERE cat_name='".$find_term."' AND category_nicename='".$find_term_slug."'" );
		$replace_match = $wpdb->get_results( "SELECT category_nicename FROM wp_sitecategories WHERE slug='".$replace_term_slug."'" );
		
		if ( $find_match && !$replace_match ) { 
			$wpdb->get_results( "UPDATE wp_sitecategories SET cat_name=REPLACE( cat_name,'".$find_term."','".$replace_term."') WHERE cat_name='".$find_term."' AND category_nicename='".$find_term_slug."'" );
			
			// we need to test to see if the replace was sucessful. because SELECT is not case sensitive but REPLACE is
			if ( $wpdb->get_results( "SELECT cat_name FROM wp_sitecategories WHERE cat_name='".$replace_term."' AND category_nicename='".$find_term_slug."'" ) ) {
				$wpdb->get_results( "UPDATE wp_sitecategories SET category_nicename=REPLACE( category_nicename,'".$find_term_slug."','".$replace_term_slug."') WHERE category_nicename='".$find_term_slug."'" );
				//echo "<b>SUCCESS!</b> In the global category table <i>".$find_term."</i> was renamed to <i>".$replace_term."</i>.<br>";
			//} else {
				//echo "A match was found in the global category table, but the case did not match, so the replace was not performed.<br>";
			} 
			
			//} elseif ( $find_match && $replace_match ) { 
			//	echo "<b>WARNING:</b> In the global category table <i>".$replace_term."</i> already exists, so it cannot be replaced. (duplicates are not allowed)<br>"; 
			//} else {
			//	echo "No matches found in the global category table<br>";
		
		}		
		
		echo '</p></div>';
		
	}
	
	// Show the admin form
	$catdefault_options = get_option('catdefault_options');
	$max_default_cats = get_site_option( 'max_default_cats' );
	if ( $max_default_cats=="" ) { $max_default_cats = 6; }
	?>
	<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> 
	<div class="wrap"> 
		<h2>Defaults Settings for New Blogs</h2> 
		<h3>Default Categories</h3> 
		<table class="form-table">
			<tr valign="top">
				<th scope="row">Number of Default Categories</th> 
				<td><input name="max_default_cats" type="text" value="<?php echo $max_default_cats; ?>" size="3" /> 
					Click the update button below for this to take effect.</td> 
			</tr>
		<?php for ( $i=1; $i<=$max_default_cats; $i++) { ?>
			<tr valign="top">
				<th scope="row">Category <?php echo $i; ?></th> 
				<td><input name="default_cat_<?php echo $i; ?>" type="text" style="width: 95%" value="<?php echo get_site_option( 'default_cat_'.$i ); ?>" size="40" /><br />
				</td> 
			</tr>
			<?php } // end for loop ?>
		</table>
		<p class="submit"><input type="submit" name="Submit" class="button" value="Save Changes" /></p>
	</div>
	</form> 
	<p>&nbsp;</p>
	<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> 
		<div class="wrap"> 
			<h2>Manage Existing Blogs</h2>
			<p style="color:red;">Warning: Make sure you have a full backup of your database (or at least the wp_#_terms tables for each blog) before proceeding!</p>
			<h3>Add Default Categories to All Existing Blogs</h3>
			<p>This update will add the above categories to all blogs, it will not change the names of existing categories. <br>
			Note: Save the above list before clicking the button below.</p>
			<p><input type="submit" name="do" value="Add Categories" class="button" onclick="return confirm('Are You sure you want to add the categories listed above to ALL existing blogs?')" /></p>
			</div> 
	</form>
	<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> 
		<div class="wrap"> 			
			<h3>Find and Replace Category Names in All Existing Blogs</h3>
			<p>Use this form to change existing category names for all blogs. For example: Change Uncategorized to another name. Only Exact Matches are replaced: it is case sensitive, partial terms are not replaced.</p>
			<p>Find this term: 
			<input type="text" name="find_term"> and replace it with this term: <input type="text" name="replace_term"> 
			<input type="submit" name="do" value="Find and Replace Categories"  class="button" onclick="return confirm('Are You sure you perform a find and replace on Category names for ALL existing blogs?')"/></p>
		</div> 
	</form>
<?php
} // end main function

add_action('admin_menu', 'cat_defaults_options_page');
function cat_defaults_options_page() {
	get_currentuserinfo();
	if (!is_site_admin()) return false;
	add_submenu_page('wpmu-admin.php', 'Category Default Options', 'Category Defaults', 10, 'cat_defaults', 'cat_default_options');
}

// when a new blog is created, add the default categories
function default_category( $blog_id )  {
	
	switch_to_blog( $blog_id );
	
	$max_default_cats = get_site_option('max_default_cats');
	for ( $i=1; $i<=$max_default_cats; $i++) {
		$cat_name = get_site_option( 'default_cat_'.$i );
		if ( $cat_name != "" ) {
			$category = array(
				'cat_name' => $cat_name, 
				'category_parent' => '', 
				'category_description' => ''
				);
			wp_insert_category( $category );
		}
	}
	
	restore_current_blog();	
    return;
}
add_action('wpmu_new_blog', 'default_category');

?>